package com.project.lvshi.controller.cases;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.project.lvshi.domain.Result;
import com.project.lvshi.domain.SysCase;
import com.project.lvshi.domain.SysOrder;
import com.project.lvshi.domain.User;
import com.project.lvshi.enums.ResultCode;
import com.project.lvshi.service.SysCaseService;
import com.project.lvshi.service.SysOrderService;
import com.project.lvshi.service.UserService;
import com.project.lvshi.utils.TokenUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.Duration;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author 超级管理员
 * @version 1.0
 * @description: 案件controller
 * @date 2024/04/18 09:19
 */
@Controller
@ResponseBody
@RequestMapping("case")
public class SysCaseController {

    @Autowired
    private SysCaseService sysCaseService;
    @Autowired
    private UserService userService;
    @Autowired
    private SysOrderService sysOrderService;

    /** 分页获取案件 */
    @PostMapping("getSysCasePage")
    public Result getSysCasePage(@RequestBody SysCase sysCase) {
        Page<SysCase> page = new Page<>(sysCase.getPageNumber(),sysCase.getPageSize());
        QueryWrapper<SysCase> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .like(StringUtils.isNotBlank(sysCase.getLawyerId()),SysCase::getLawyerId,sysCase.getLawyerId())
                .like(StringUtils.isNotBlank(sysCase.getLawyerName()),SysCase::getLawyerName,sysCase.getLawyerName())
                .like(StringUtils.isNotBlank(sysCase.getName()),SysCase::getName,sysCase.getName())
                .like(StringUtils.isNotBlank(sysCase.getContent()),SysCase::getContent,sysCase.getContent())
                .eq(sysCase.getState() != null,SysCase::getState,sysCase.getState())
                .eq(StringUtils.isNotBlank(sysCase.getUserId()),SysCase::getUserId,sysCase.getUserId())
                .eq(StringUtils.isNotBlank(sysCase.getCreateBy()),SysCase::getCreateBy,sysCase.getCreateBy())
                .eq(sysCase.getCreateTime() != null,SysCase::getCreateTime,sysCase.getCreateTime());
        Page<SysCase> sysCasePage = sysCaseService.page(page, queryWrapper);
        return Result.success(sysCasePage);
    }

    /** 根据id获取案件 */
    @GetMapping("getSysCaseById")
    public Result getSysCaseById(@RequestParam("id")String id) {
        SysCase sysCase = sysCaseService.getById(id);
        return Result.success(sysCase);
    }

    /** 保存案件 */
    @PostMapping("saveSysCase")
    public Result saveSysCase(@RequestBody SysCase sysCase) {
        String id = TokenUtils.getUserIdByToken();
        sysCase.setUserId(id);
        User user = userService.getById(sysCase.getLawyerId());
        sysCase.setLawyerName(user.getUserName());
        boolean save = sysCaseService.save(sysCase);
        if (save) {
            if (user.getCaseMoney() > 0) {
                SysOrder sysOrder = new SysOrder();
                sysOrder.setType(1);
                sysOrder.setUserId(id);
                sysOrder.setLayerId(user.getId());
                sysOrder.setMoney(user.getCaseMoney());
                sysOrderService.save(sysOrder);
            }
            return Result.success();
        } else {
            return Result.fail(ResultCode.COMMON_DATA_OPTION_ERROR.getMessage());
        }
    }

    /** 编辑案件 */
    @PostMapping("editSysCase")
    public Result editSysCase(@RequestBody SysCase sysCase) {
        boolean save = sysCaseService.updateById(sysCase);
        if (save) {
            return Result.success();
        } else {
            return Result.fail(ResultCode.COMMON_DATA_OPTION_ERROR.getMessage());
        }
    }

    /** 删除案件 */
    @GetMapping("removeSysCase")
    public Result removeSysCase(@RequestParam("ids")String ids) {
        if (StringUtils.isNotBlank(ids)) {
            String[] asList = ids.split(",");
            for (String id : asList) {
                sysCaseService.removeById(id);
            }
            return Result.success();
        } else {
            return Result.fail("案件id不能为空！");
        }
    }

    @GetMapping("getCaseAnalysis")
    public Result getCaseAnalysis() {
        JSONObject jsonObject = new JSONObject();
        //案件数量
        int count = sysCaseService.count();
        jsonObject.put("count", count);
        //类型分析
        QueryWrapper<SysCase> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("sum(1) as count,type").lambda().groupBy(SysCase::getType);
        List<Map<String, Object>> listMaps = sysCaseService.listMaps(queryWrapper);
        jsonObject.put("list",listMaps);
        List<Object> type = new ArrayList<>();
        List<Object> counts = new ArrayList<>();
        for (Map<String, Object> map : listMaps) {
            type.add(map.get("type"));
            counts.add(map.get("count"));
        }
        jsonObject.put("type",type);
        jsonObject.put("counts",counts);
        //案件时长分析
        QueryWrapper<SysCase> query = new QueryWrapper<>();
        query.lambda().eq(SysCase::getState,4);
        List<SysCase> list = sysCaseService.list(query);
        List<String> names = new ArrayList<>();
        List<Object> times = new ArrayList<>();
        for (SysCase sysCase : list) {
            names.add(sysCase.getName());
            long l = sysCase.getUpdateTime().getTime() - sysCase.getCreateTime().getTime();
            Float l1 = (float) l / (1000 * 60 * 60);
            times.add(l1);
        }
        jsonObject.put("names", names);
        jsonObject.put("times", times);
        return Result.success(jsonObject);
    }

}
